package com.yxuan.springboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.yxuan.springboot.mapper.SchoolInformationMapper;
import com.yxuan.springboot.mapper.VolunteerFormDetailsMapper;
import com.yxuan.springboot.mapper.VolunteerFormMapper;
import com.yxuan.springboot.model.VolunteerForm;
import com.yxuan.springboot.model.VolunteerFormDetails;
import com.yxuan.springboot.service.VolunteerFormService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;

/**
 * @author zchao
 * VolunteerForm业务层实现类
 * @date 2023-06-16 16:54:06
 */
@Service
@Transactional
@Slf4j
public class VolunteerFormServiceImpl extends BaseServiceImpl<VolunteerForm> implements VolunteerFormService {


    @Autowired
    private VolunteerFormMapper volunteerFormMapper;

    @Autowired
    private VolunteerFormDetailsMapper volunteerFormDetailsMapper;

    @Autowired
    private SchoolInformationMapper schoolInformationMapper;

    @Override
    public HashMap<String, Object> saveVolunteerform(Map map) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        int trueId = 0;
//         判断是新增还是修改,修改则将原数据全部做逻辑删除
        if (map.get("id") != null) {
//            给志愿表做逻辑删除
            int id = (int) map.get("id");
            VolunteerForm form = new VolunteerForm();
            form.setTrueFormId(id);
            form.setLogicalDelete("0");
            VolunteerForm volunteerForm = volunteerFormMapper.queryObjectByPramas(form);
            trueId = (int) map.get("id");

            volunteerForm.setLogicalDelete("1");
            volunteerFormMapper.update(volunteerForm);
//            给志愿详情表做逻辑删除
            VolunteerFormDetails delVolunteerDetails = new VolunteerFormDetails();
            delVolunteerDetails.setFormId(id);
            List<VolunteerFormDetails> volunteerFormDetailsList = volunteerFormDetailsMapper.queryListByPramas(delVolunteerDetails);
            for (VolunteerFormDetails entity : volunteerFormDetailsList) {
                entity.setLogicalDelete("1");
                volunteerFormDetailsMapper.update(entity);
            }
        }

//        1.保存志愿表基本信息
        Timestamp timestamp = new Timestamp(new Date().getTime());
        VolunteerForm volunteerForm = new VolunteerForm();
        volunteerForm.setUserId((Integer) map.get("userId"));
        volunteerForm.setProvince(String.valueOf(map.get("province")));
        volunteerForm.setScore(String.valueOf(map.get("score")));
        volunteerForm.setCourseSelection(String.valueOf(map.get("courseSelection")));
        volunteerForm.setLogicalDelete("0");
        volunteerForm.setCreateTime(timestamp);
        volunteerFormMapper.insert(volunteerForm);
//        获取保存的表信息
        VolunteerForm volunteerForm1 = volunteerFormMapper.queryObjectByPramas(volunteerForm);
        if (trueId == 0) {
            volunteerForm1.setTrueFormId(volunteerForm.getId());
        } else {
            volunteerForm1.setTrueFormId(trueId);
        }
        volunteerFormMapper.update(volunteerForm1);
        int averageRate = 0;
        int count = 0;
//         2. 保存表中的学校以及专业信息
        for (Object sch : (List) map.get("applicationSchool")) {
            Map<String, Object> schoolinfo = BeanUtil.beanToMap(sch);
            averageRate += (Integer) schoolinfo.get("rate");
            count += 1;
//            3.获取专业信息,并添加
            for (Object pro : (List) schoolinfo.get("professionList")) {
                VolunteerFormDetails volunteerFormDetails = new VolunteerFormDetails();
                volunteerFormDetails.setSchoolId((Integer) schoolinfo.get("schoolId"));
                volunteerFormDetails.setSchoolRate((Integer) schoolinfo.get("rate"));
                volunteerFormDetails.setSchoolSort((Integer) schoolinfo.get("sort"));
                volunteerFormDetails.setFormId(volunteerForm1.getId());
                Map<String, Object> professioninfo = BeanUtil.beanToMap(pro);
                volunteerFormDetails.setMajorName(String.valueOf(professioninfo.get("professionName")));
                volunteerFormDetails.setMajorRate((Integer) professioninfo.get("rate"));
                volunteerFormDetails.setProfessionSort((Integer) professioninfo.get("sort"));
                volunteerFormDetails.setLogicalDelete("0");
                volunteerFormDetailsMapper.insert(volunteerFormDetails);
            }
        }
        volunteerForm.setAverageRate(averageRate / count);
        volunteerFormMapper.update(volunteerForm);
        result.put("save", "success");
        return result;
    }


    //    根据用户id查找所有志愿表信息
    @Override
    public HashMap<String, Object> volunteerformList(Map map) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        VolunteerForm volunteerForm = new VolunteerForm();
        volunteerForm.setUserId((Integer) map.get("userId"));
        volunteerForm.setLogicalDelete("0");
        List<VolunteerForm> volunteerFormsById = volunteerFormMapper.queryListByPramas(volunteerForm);
//        list倒序排列
        Collections.reverse(volunteerFormsById);
        List list = new ArrayList<>();
        for (VolunteerForm f : volunteerFormsById) {
            HashMap<String, Object> form = new HashMap<>();
            form.put("formId", f.getTrueFormId());
            form.put("score", f.getScore());
            form.put("courseSelection", f.getCourseSelection());
            form.put("averageRate", f.getAverageRate());
            form.put("province", f.getProvince());
            list.add(form);
        }
        result.put("list", list);
        return result;
    }

    @Override
    public HashMap<String, Object> volunteerformDetails(Map map) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        int formid = (int) map.get("id");
        VolunteerForm form1 = new VolunteerForm();
        form1.setTrueFormId(formid);
        form1.setLogicalDelete("0");
        VolunteerForm form2 = volunteerFormMapper.queryObjectByPramas(form1);
        VolunteerForm form = volunteerFormMapper.queryObjectById(String.valueOf(form2.getId()));
        List<Integer> idList = volunteerFormDetailsMapper.findSchoolIdList(form2.getId());
//            学校信息  查询学校信息
        List<Map> maps = volunteerFormDetailsMapper.findschoolDetails(idList);
        for (Map s : maps) {
            VolunteerFormDetails volunteerFormDetails = new VolunteerFormDetails();
            volunteerFormDetails.setSchoolId((Integer) s.get("id"));
            volunteerFormDetails.setFormId(form.getId());
            List<VolunteerFormDetails> detailsList = volunteerFormDetailsMapper.queryListByPramas(volunteerFormDetails);
            s.put("schoolRate", detailsList.get(0).getSchoolRate());
            s.put("schoolSort", detailsList.get(0).getSchoolSort());
        }
        List list = new ArrayList<>();
        for (Map m : maps) {
//            将学校成绩添加到map
            List<String> classificationListsch = new ArrayList<>();
            String courseSelectionsch = form.getCourseSelection();
            classificationListsch.add("综合");
            if (courseSelectionsch.contains("物")) {
                classificationListsch.add("物理类");
                classificationListsch.add("理科");
            } else {
                classificationListsch.add("历史类");
                classificationListsch.add("文科");
            }

            List<Map> schoolScore = volunteerFormDetailsMapper
                    .findSchoolScore(form.getProvince(), String.valueOf(m.get("school_name")), classificationListsch);
            m.put("schoolscore", schoolScore);
//            添加该学校的专业信息,根据专业名，schoolId，
            VolunteerFormDetails volunteerFormDetails = new VolunteerFormDetails();
            volunteerFormDetails.setFormId(form.getId());
            volunteerFormDetails.setSchoolId((Integer) m.get("id"));
            volunteerFormDetails.setLogicalDelete("0");
            List<VolunteerFormDetails> volunteerFormDetails1 = volunteerFormDetailsMapper.queryListByPramas(volunteerFormDetails);
            log.info(volunteerFormDetails1.toString() +" ++++++++");
            List list1 = new ArrayList<>();
            for (VolunteerFormDetails f : volunteerFormDetails1) {
                HashMap<String, Object> professions = new HashMap<>();
                List<String> classificationList = new ArrayList<>();
                String courseSelection = form.getCourseSelection();
                classificationList.add("综合");
                if (courseSelection.contains("物")) {
                    classificationList.add("物理类");
                    classificationList.add("理科");
                } else {
                    classificationList.add("历史类");
                    classificationList.add("文科");
                }
                log.info(f.getSchoolId() + " ++++++++++++++++++++++++++");
                List<Map> professionScore = volunteerFormDetailsMapper.findProfessionScore(f.getSchoolId(), f.getMajorName(), form.getProvince(), classificationList);
                professions.put("proScoreDetails", professionScore);
                professions.put("professionSort", f.getProfessionSort());
                professions.put("professionRate", f.getMajorRate());
                list1.add(professions);
            }
            m.put("professionScore", list1);
            list.add(m);
            result.put("info", list);
        }
        return result;
    }

    @Override
    public HashMap<String, Object> countVolunteerform(Map map) {
        HashMap<String, Object> result = new HashMap<>();
        int num = volunteerFormMapper.countFormByUserId((int) map.get("user_id"));
        result.put("countId", num);
        return result;
    }

    @Override
    public HashMap<String, Object> delVolunteerform(Map map) throws Exception {
        HashMap<String, Object> result = new HashMap<>();
        VolunteerForm form = new VolunteerForm();
        form.setTrueFormId((int) map.get("trueFormId"));
        //        删除表的详细数据
        List<VolunteerForm> volunteerForms = volunteerFormMapper.queryListByPramas(form);
        for (VolunteerForm v : volunteerForms){
            VolunteerFormDetails volunteerFormDetails = new VolunteerFormDetails();
            volunteerFormDetails.setFormId(v.getId());
            volunteerFormDetailsMapper.delete(volunteerFormDetails);
        }
//       删除form表数据
        for (VolunteerForm f:volunteerForms){
            volunteerFormMapper.delete(f);
        }
        result.put("del", "success");
        return result;
    }
}
